package com.kgc.ssm.service.impl;

import com.kgc.ssm.entity.dto.QuoteDe;
import com.kgc.ssm.entity.dto.Result;
import com.kgc.ssm.mapper.QuoteDeMapper;
import com.kgc.ssm.service.QuoteDeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;
@Service

public class QuoteDeServiceImpl implements QuoteDeService {
    @Resource
    private QuoteDeMapper quoteDeMapper;

    @Override
    public List<QuoteDe> selectByTitles(String[] queTitle) {
        return quoteDeMapper.selectByTitles(queTitle);
    }

    @Override
    public List<QuoteDe> selectByMaterialCode(String[] materialCode) {
        return quoteDeMapper.selectByMaterialCode(materialCode);
    }

    @Override
    @Transactional
    public Result<QuoteDe> updateQuoteDe(List<QuoteDe> formDatas) {
        try {
            // 遍历并更新数据库
            for (QuoteDe item : formDatas) {
                int updateQuoteResult = quoteDeMapper.updateQuote(item);
                int updateEnquireResult = quoteDeMapper.updateEnquire(item);
                int updateQuoteDetailResult = quoteDeMapper.updateQuoteDetail(item);

                // 检查更新结果，如果更新失败，抛出异常
                if (updateQuoteResult <= 0) {
                    throw new RuntimeException("更新 QUOTE 表失败，ID：" + item.getQuoteId());
                }
                if (updateEnquireResult <= 0) {
                    throw new RuntimeException("更新 ENQUIRE 表失败，ID：" + item.getEnquireId());
                }
                if (updateQuoteDetailResult <= 0) {
                    throw new RuntimeException("更新 QUOTE_DETAIL 表失败，ID：" + item.getQuoteDetailId());
                }
            }
            // 如果所有更新都成功，返回成功的 Result 对象
            return new Result<>("更新报价信息成功", 200, null);

        } catch (Exception e) {
            System.out.println("更新报价信息失败"+e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result<>("更新报价信息失败", 500, null);
        }
    }
}
